<?php

session_start();
if (Mylits_Config::getValue('development')) {
    error_reporting(E_ALL);
} else {
    error_reporting(0);
}

/**
 * @version     1.0.0
 * @package     mylits engine
 * @license     GNU General Public License version 3
 * @author      Arfan Fudyartanto D N <arfan@mylits.com> - http://engine.mylits.com
 */
class Mylits {

    public $base_theme;
    public $theme;
    public $component;
    public $widgets;
    public $header = '';
    public $loader = '<div id="ajax-loader"></div>';
    private $message = '';
    private $styles = array();
    private $scripts = array();
    private $model;
    private $startTime;
    private $endTime;
    private $version = '1.0';
    private static $instance;

    public function __construct() {
        $this->startTime = microtime(true);
        define('MYLITS', 'mylits.com');
        $_SESSION['doc']['styles'] = array();
        $_SESSION['doc']['scripts'] = array();
        if (!isset($_SESSION['SYS_MSG'])) {
            $_SESSION['SYS_MSG'] = array();
        }
        #require order file is important !, please don't change them
        require_once 'core/classes/messenger.php';
        require_once 'core/classes/client.php';
        require_once 'core/classes/user.php';
        require_once 'core/classes/template.php';
        require_once 'core/classes/security.php';
        require_once 'core/classes/system.php';
        require_once 'core/classes/loader.php';
        require_once 'core/classes/model.php';
        require_once 'core/classes/controller.php';
        require_once 'core/classes/language.php';
        require_once 'core/classes/error.php';
        require_once 'core/classes/process.php';
        require_once 'core/classes/document.php';

        #initial object;
        Mylits_Language::init();

        if (Mylits_Config::issetParam('db')) {
            $this->model = Mylits_Loader::getModel('main', ENGINE_DIR . '/core/models/main.mdls.php');
        }
    }

    public static function getInstance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function setConfig($config) {
        $this->config = $config;
    }

    public function addStyle($path, $weight = NULL) {
        if (!empty($weight)) {
            if (!in_array($path, $_SESSION['doc']['styles'])) {
                $_SESSION['doc']['styles'][$weight] = $path;
            }
        } else {
            $_SESSION['doc']['styles'][] = $path;
        }
    }

    public function addScript($path, $weight = NULL) {
        if (!empty($weight)) {
            if (!in_array($path, $_SESSION['doc']['scripts'])) {
                $_SESSION['doc']['scripts'][$weight] = $path;
            }
        } else {
            $_SESSION['doc']['scripts'][] = $path;
        }
    }

    public function result() {
        $str_params = isset($_GET['params']) ? $_GET['params'] : Mylits_Config::getValue('default_component');

        #replace ending slash without char follow
        $get = preg_replace('/\/$/', '', $str_params);
        if (Mylits_Config::issetParam('db')) {
            $get = $this->model->getRealPath($get);
        }
        #find component name
        $component = strpos($get, '/') ? substr($get, 0, strpos($get, '/')) : $get;

        #get theme
        if (Mylits_Config::issetParam('db')) {
            $this->theme = $this->model->getActiveTemplates();
        } else {
            $this->theme = Mylits_Config::getValue('template');
        }

        $controller = Mylits_Loader::getController($component);
        #find params and explode as array 
        $params = strpos($get, '/') ? explode('/', str_replace($component . '/', '', $get)) : array();

        if (is_object($controller)) {
            $controller->task = isset($params[0]) ? $params[0] : '';
            if (isset($params[0])) {
                unset($params[0]);
            }
            $controller->params = array_values($params);
            if ($controller->is_public) {
                $this->component = $controller->view();
            } else {
                $user = Mylits_User::getInstance();
                if ($user::$guest) {
                    $this->component = "Permission denied";
                } elseif ($this->model->checkComponentPermission($component)) {
                    #$this->component = $controller->view($params);
                    $this->component = $controller->view();
                } else {
                    $this->component = "Permission denied";
                }
            }
        }
        $this->component = Mylits_System::getRenderedObject($this->component);
        $this->compileMessage();
        $html = '';
        if (Mylits_System::isAjaxRequest() || Mylits_System::issetRequest('raw')) {
            $this->compileHeader();
            $this->header = '<header>' . $this->header . '</header>';
            $html = $this->header . $this->message . $this->component;
        } else {
            $this->component = '<div class="main-component">' . $this->message . $this->component . '</div>';
            $this->base_theme = BASE_URL . 'templates/' . $this->theme . '/';

            $html = $this->cleanHtml();

            #read rendered component object
            $html = Mylits_System::getRenderedObject($html);

            $this->endTime = microtime(true);

            if (Mylits_Config::getValue('development') && Mylits_Config::issetParam('logs')) {
                $logs = Mylits_Config::getValue('logs');
                if (!empty($logs)) {
                    $executionTime = ($this->endTime - $this->startTime);
                    $content = "\n" .
                            'Memory usage   : ' . memory_get_usage() . ' bytes' . "\n" .
                            'Execution time : ' . $executionTime . ' microseconds' . "\n" .
                            '----------------------------------------------------------';
                    $logsFile = Mylits_Config::getValue('logs') . '/logs.txt';
                    if (is_file($logsFile)) {
                        $content = file_get_contents($logsFile) . $content;
                    }
                    $fp = fopen($logsFile, "w");
                    fwrite($fp, $content);
                    fclose($fp);
                }
            }
        }
        return $html;
    }

    private function cleanHtml() {
        $html = '';
        $this->compileHeader();
        if (Mylits_Config::issetParam('db')) {
            $this->loadWidgets();
        }
        $this->compileMessage();
        if (is_file(APP_DIR . '/templates/' . $this->theme . '/index.php')) {
            ob_start();
            include APP_DIR . '/templates/' . $this->theme . '/index.php';
            $html = ob_get_clean();
        } else {
            echo 'Please check template file, current template pointer is : ' . $this->theme;
        }
        $path = APP_DIR . '/templates/' . $this->theme . '/index.php';
        return $html;
    }

    private function compileMessage() {
        foreach ($_SESSION['SYS_MSG'] as $msgItem) {
            $this->message .= '<div class="alert alert-' . $msgItem['class'] . ' fade in">
                <button class="close" aria-hidden="true" data-dismiss="alert" type="button">x</button>' . $msgItem['message'] . '</div>';
        }
        $_SESSION['SYS_MSG'] = array();
    }

    private function compileHeader() {
        foreach ($_SESSION['doc']['scripts'] as $script) {
            $this->header .= '<script type="text/javascript" src="' . $script . '"></script>' . "\n";
        }
        foreach ($_SESSION['doc']['styles'] as $style) {
            $this->header .= '<link rel="stylesheet" type="text/css" href="' . $style . '"/>' . "\n";
        }
        unset($_SESSION['doc']);
        #add javascript variable
        $this->header .= ''
                . '<script type="text/javascript">'
                . 'var BASE_URL = "' . BASE_URL . '"'
                . '</script>';
        return $this->header;
    }

    private function loadWidgets() {
        if (is_file(APP_DIR . '/templates/' . $this->theme . '/config.php')) {
            include APP_DIR . '/templates/' . $this->theme . '/config.php';

            foreach ($template['position'] as $mName => $rName) {
                $wList = $this->model->getWidgetList($mName);
                $wListResult = '';
                foreach ($wList as $widget) {
                    $wHtml = '';
                    $wName = $widget['name'];
                    $comp = Mylits_Loader::getController($wName);
                    $comp->widget_id = $widget['id'];
                    $comp->widgetParams = json_decode($widget['params']);
                    if ($comp->is_public) {
                        $wHtml = $comp->view();
                        $wListResult .= "\n" . $wHtml;
                    } else {
                        $user = Mylits_User::getInstance();
                        if ($user::$guest) {
                            $wHtml = "Permission denied";
                        } elseif ($this->model->checkComponentPermission($mName)) {
                            $wHtml = $comp->view();
                        } else {
                            $wHtml = "Permission denied";
                        }
                    }
                }
                @$this->widgets->$mName = $wListResult;
            }
        } else {
            echo 'config.php not found in ' . $this->theme . ' template';
        }
    }

}

?>
